import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';
import type Tenant from './Tenant.model';
import type Company from './Company.model';
import type User from './User.model';

/**
 * 部门模型
 */
class Department extends Model {
  public id!: string;
  public tenantId!: string;
  public companyId!: string;
  public parentId?: string;
  public name!: string;
  public code?: string;
  public managerId?: string;
  public phone?: string;
  public email?: string;
  public description?: string;
  public level!: number;
  public path?: string;
  public status!: 'active' | 'inactive';
  public sortOrder!: number;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public deletedAt?: Date;

  // 关联属性
  public tenant?: Tenant;
  public company?: Company;
  public parent?: Department;
  public children?: Department[];
  public manager?: User;
  public users?: User[];

  /**
   * 是否活跃
   */
  isActive(): boolean {
    return this.status === 'active';
  }

  /**
   * 是否顶级部门
   */
  isTopLevel(): boolean {
    return !this.parentId;
  }

  /**
   * 获取部门层级路径数组
   */
  getPathArray(): string[] {
    if (!this.path) return [];
    return this.path.split('/').filter(Boolean);
  }
}

Department.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'tenant_id',
    },
    companyId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'company_id',
    },
    parentId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'parent_id',
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    code: {
      type: DataTypes.STRING(50),
      allowNull: true,
    },
    managerId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'manager_id',
    },
    phone: {
      type: DataTypes.STRING(50),
      allowNull: true,
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    level: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 1,
    },
    path: {
      type: DataTypes.STRING(500),
      allowNull: true,
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive'),
      allowNull: false,
      defaultValue: 'active',
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'sort_order',
    },
  },
  {
    sequelize,
    tableName: 'departments',
    underscored: true,
    paranoid: true,
    timestamps: true,
  },
);

export default Department;

